package com.example.mmlist2.utils;

import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import androidx.documentfile.provider.DocumentFile;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.example.mmlist2.storage.DatabaseHelper;
import com.example.mmlist2.storage.entity.Account;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.util.stream.Collectors;

public class FileImportExport {

    //插入导入数据
    public static void insert(Context context, Uri uri) {

        // 使用 try-with-resources 自动关闭 InputStream
        try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) {
            if (inputStream != null) {
                // 将输入流转换为 JSON 对象
                Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
                String jsonString = scanner.hasNext() ? scanner.next() : "";
                jsonString = jsonString.replace("}\\n    \"}", "");
                // 将 JSON 字符串转换回 Map
                Type type = new TypeReference<Map<String, Object>>() {
                }.getType();
                Map<String, Object> map = JSON.parseObject(jsonString, type);
                Object accountsObj = map.get("accounts");
                String accountsKey = (String) map.get("key");
                SharedPreferences sharedPreferences = context.getSharedPreferences("MyPreferences", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("pass", accountsKey);
                editor.apply();
                if (accountsObj instanceof List) {
                    // 类型转换
                    Type listTypeRef = new TypeReference<List<Map<String, Object>>>() {
                    }.getType();
                    List<Map<String, Object>> accounts = JSON.parseObject(JSON.toJSONString(accountsObj), listTypeRef);
                    // 提取数据
                    newAddAccount(accounts, context.getApplicationContext());
                    // 刷新 ListFragment 的数据
                    refreshListFragment(context.getApplicationContext());
                    Toast.makeText(context, "导入成功", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (JSONException e) {
            Log.e("JSONException", Objects.requireNonNull(e.getLocalizedMessage()));
            Toast.makeText(context, "请导入合适的json文件", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //覆盖本地数据库
    private static void newAddAccount(List<Map<String, Object>> list, Context context) {
        List<Account> accounts;
        accounts = list.stream()
                .map(map -> {
                    Account account = new Account();
                    Integer id = (Integer) map.get("id");
                    if (id == null) {
                        // 如果ID为null，返回null，后面在filter中会将其过滤掉
                        return null;
                    }
                    account.setId(id);
                    account.setUsername((String) map.get("username"));
                    account.setPassword((String) map.get("password"));
                    account.setTitle((String) map.get("title"));
                    account.setLink((String) map.get("link"));
                    account.setIllustrate((String) map.get("illustrate"));
                    return account;
                })
                .collect(Collectors.toList());
        DatabaseHelper db = new DatabaseHelper(context);
        try {
            db.newAccount(accounts);
        } catch (Exception e) {
            Log.e("downloadError", Objects.requireNonNull(e.getLocalizedMessage()));
        }
        db.close();
    }

    // 刷新 ListFragment 的数据
    private static void refreshListFragment(Context context) {
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
        Intent intent = new Intent("com.example.mmList2.REFRESH_LIST");//这里要与上面注册的要一样
        localBroadcastManager.sendBroadcast(intent);//发送本地广播
    }

    // 保存数据到文件
    public static void saveFile(Context context, String json, Uri uri) {
        // 将保存文件的逻辑放在这个方法中

        context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        // 使用DocumentFile.fromTreeUri获取指定目录下的文件
        DocumentFile documentFile = DocumentFile.fromTreeUri(context, uri);
        if (documentFile == null) {
            Toast.makeText(context, "选择的不是目录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 查找名为 data.json 的文件
        DocumentFile existingFile = findFileByName(documentFile);

        if (existingFile != null && existingFile.isFile()) {
            // 文件已存在，清空文件内容
            try (OutputStream outputStream = context.getContentResolver().openOutputStream(existingFile.getUri())) {

                // 写入新的数据
                OutputStreamWriter writer = new OutputStreamWriter(outputStream);
                BufferedWriter bufferedWriter = new BufferedWriter(writer);
                bufferedWriter.write(json);
                bufferedWriter.close();
                Toast.makeText(context, "导出成功", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Log.e("saveFile", e.getClass().getName());
                Toast.makeText(context, "导出失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 文件不存在，创建新文件
            DocumentFile newFile = documentFile.createFile("application/text", "data.json");
            if (newFile != null) {
                // 文件创建成功，可以在这里进行后续操作，例如写入数据
                try (OutputStream outputStream = context.getContentResolver().openOutputStream(Objects.requireNonNull(newFile.getUri()))) {
                    // 将字符串写入文件
                    OutputStreamWriter writer = new OutputStreamWriter(outputStream);
                    BufferedWriter bufferedWriter = new BufferedWriter(writer);
                    bufferedWriter.write(json);
                    Toast.makeText(context, "导出成功", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    Log.e("saveFile", e.getClass().getName());
                    Toast.makeText(context, "导出失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                // 文件创建失败，可以在这里处理错误情况
                Toast.makeText(context, "文件创建失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 查找该文件是否存在
    private static DocumentFile findFileByName(DocumentFile parent) {
        for (DocumentFile file : parent.listFiles()) {
            if ("data.json".equals(file.getName())) {
                return file;
            }
        }
        return null;
    }

    // 保存 URI 到 SharedPreferences
    public static void saveUriToSharedPreferences(Context context, Uri uri) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("MyPreferences", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("saved_uri", uri.toString());
        editor.apply();
    }

    // 从 SharedPreferences 读取 URI
    public static Uri getSavedUriFromSharedPreferences(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("MyPreferences", MODE_PRIVATE);
        String savedUriString = sharedPreferences.getString("saved_uri", null);
        return savedUriString != null ? Uri.parse(savedUriString) : null;
    }


}
